
import _ from 'lodash'
import protoAPI from '../../config/proto-api'
import { types, filter } from '../../proxys/proto'
import { CODE } from '../../error'

export const asyncSend = (auth, req, res, next) => {
  let { tag } = req.params
  let setting = _.find(protoAPI, o => o.name === tag)
  let options = {}
  if (setting) {
    let { params } = setting
    for (let key of _.keys(params)) {
      let value = _.trim(req.body[key] || '')
      let valid = params[key]
      let validArr = valid.replace(/^(\!)/, '').split(/\|/)
      let validTrue = false
      for (let e of validArr) {
        if (types[e](value)) {
          validTrue = true
          break
        }
      }
      if (!/^(\!)/.test(valid) && _.isEmpty(value)) {
        // 不允许空值
        return res.api(null, CODE.ERROR_VALID_FIELD_REQUIRED, [key])
      }
      if (!validTrue) {
        // 字段格式错误
        return res.api(null, CODE.ERROR_VALID_FIELD_FORMAT, [key])
      }
      options[key] = filter(value, valid)
    }
  }
  return next({ name: tag, opts: options, auth })
}